//gulp入口文件

const { src, dest, parallel, series, watch } = require('gulp')
const del = require('del')
const browserSync = require('browser-sync') //用于创建服务器
const loadPlugins = require('gulp-load-plugins')

const plugins = loadPlugins() 
const bs = browserSync.create()

const data = {  //配置一些数据
    menus: [],
    pkg: require('./package.json'),
    date: new Date()
}

const clean = () => {
    return del(['dist', 'temp'])
}

const style = () => {
    return src('src/assets/styles/*.scss', { base: 'src' })
        .pipe(plugins.sass({ outputStyle: 'expanded' }))
        .pipe(dest('temp'))
}

const script = () => {
    return src('src/assets/scripts/*.js', {base: 'src'})
        .pipe(plugins.babel({presets: ['@babel/preset-env'] }))
        .pipe(dest('temp'))
}

const page = () => {
    return src('src/*html', { base: 'src' })
        .pipe(plugins.swig({ data }))
        .pipe(dest('temp'))
}

const image = () => {
    return src('src/assets/images/**', {base: 'src' })
        .pipe(plugins.imagemin())
        .pipe(dest('dist'))
}

const font = () => {
    return src('src/assets/fonts/**', {base: 'src' })
        .pipe(plugins.imagemin())
        .pipe(dest('dist'))
}

const extra = () => {
    return src('src/pubilc/**', {base: 'public'})
        .pipe(dest('dist'))
}

const serve = () => {   //自动化构建-热更新
    watch('src/assets/styles/*.scss', style)
    watch('src/assets/script/*.js', script)
    watch('src/*.html', page)
    watch([
        'src/assets/image/**',
        'src/assets/fonts/**',
        'pubild/**',
    ], bs.reload) //这些文件变化时更新浏览器

    bs.init({
        notify: false, //关闭浏览器右上方的小提示
        port: 2000,
        files: 'dist/**', //监听自动更新浏览器
        server: {
            baseDir: ['temp', 'src', 'pubilc'], //先找数组中的第一个目录里面的内容，没有再找第二个... 开发阶段图片直接用原文件
            routes: {
                '/node_modules': 'node_modules' //先走里面的配置,再走baseDir
            }
        }
    })
}

const useref = () => {
    return src('temp/*.html', { base: 'dist' })
        .pipe(plugins.useref({ searchPath:  ['dist', '.']}))
        .pipe(plugins.if(/\.js$/, plugins.uglify()))    //自动判断对应文件路径，是否执行转换流
        .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
        .pipe(plugins.if(/\.html$/, plugins.htmlmin({ 
            collapseWhitespace: true,  //collapseWhitespace: true 压缩空格和换行
                minifyCSS: true,  //压缩页面内的css
                minifyJS: true  //压缩页面内的js
            })))
        .pipe(dest('dist')) //防止读写一个文件，会写不进去
}

const compile = parallel(style, script, page) //同时执行
//上线之前执行的任务
const build = series(clean, parallel(series(compile, useref), image, font, extra)) //先clean
//开发阶段
const develop = series(compile, serve)
module.exports = {
    clean,
    build,
    develop
} 